package servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import beans.User;
import dao.BasicUserDao;

/**
 * 执行用户注册的Servlet，用户在注册页面填写注册信息并将请求发送到本Servlet，在本Servlet中获取用户的注册信息，
 * 再调用BasicUserDao的insert方法实现向数据库中添加新的一条用户数据，完成用户注册。
 * @author Steven Suo
 *
 */
@WebServlet("/register.do")
public class UserRegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserRegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取注册页面提交的数据，并封装成User类的对象
		User user = new User();
		user.setUserName(request.getParameter("userName"));
		user.setPwd(request.getParameter("pwd"));
		//实例化BasicUserDao对象，调用BasiceUserDao对象的insert方法实现向数据库的tuser表中插入一条数据，
		//并根据insert方法返回的结果判断注册成功还是失败，注册成功则跳转到登录页面(login.html)，反之则跳转到注册页面(register.html)重新注册。
		BasicUserDao dao = new BasicUserDao();
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		if(dao.insert(user) > 0){
			out.println("注册成功，3秒后将自动跳转到登录页面。");
			response.setHeader("Refresh", "3;URL=login.html");
		}else{
			out.println("注册失败，3秒后将自动跳转到注册页面，请重新注册。");
			response.setHeader("Refresh", "3;URL=register.html");
		}
		
	}

}
